package com.tomtop.core.redis;

import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 该类特点，在写入redis时可以传入任何类对象，获取时都返回json字符串的byte[]，
 * 
 * @author lenovo
 *
 */
public class JsonBytesRedisTemplate extends RedisTemplate<String, Object> {
	public JsonBytesRedisTemplate() {
		RedisSerializer<String> stringSerializer = new StringRedisSerializer();
		RedisSerializer<Object> byteSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class) {
			public Object deserialize(byte[] bytes) {
				return bytes;
			}
		};
		setKeySerializer(stringSerializer);
		setValueSerializer(byteSerializer);
		setHashKeySerializer(stringSerializer);
		setHashValueSerializer(byteSerializer);
	}

	public JsonBytesRedisTemplate(RedisConnectionFactory connectionFactory) {
		this();
		setConnectionFactory(connectionFactory);
		afterPropertiesSet();
	}

	protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
		return new DefaultStringRedisConnection(connection);
	}
}
